/*
 ** 预约记录公用页面
 **/
import { PageContainer, ProTable } from "@ant-design/pro-components";
import {
  Button,
  Form,
  Modal,
  Drawer,
  Spin,
  Alert,
  Input,
  GetProp,
  message,
} from "antd";
import { connect, history } from "umi";
import { namespace, calcColumns } from "./configFile";
import { useState, useRef } from "react";
import AppointmentDetails from "../detail/index";
import { Fragment } from "preact";
import Https from "@/utils/Https";

const RecordList = (props) => {
  const { dispatch } = props;
  const actionRef = useRef();
  const [modal, contextHolder] = Modal.useModal();
  const [open, setOpen] = useState("");
  const [courseId, setCourseId] = useState("");
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const InputRef = useRef();
  const [title, setTitle] = useState("");
  const [messageStatus, setMessageStatus] = useState("");
  const [messageText, setMessageText] = useState("");
  //取消预约
  const cancelRecord = (params) => {
    modal.confirm({
      title: "提示",
      icon: null,
      content: "确认取消当前预约吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        dispatch({
          type: `${namespace}/cancelRecord`,
          params: {
            recordId: params.id,
          },
          callback: (res) => {
            actionRef.current && actionRef.current.reload();
          },
        });
      },
    });
  };
  //签到码改变事件
  const onChangeText: GetProp<typeof Input.OTP, "onChange"> = async (text) => {
    setLoading(true);
    InputRef.current && InputRef.current.blur();
    let params = {
      classCode: text,
      bookRecordId: courseId,
    };
    let res = await Https.get("/course/sched/signIn", params, true);
    setLoading(false);
    if (res.code == 200) {
      setMessageStatus("success");
      setTimeout(() => {
        actionRef.current && actionRef.current.reload();
        setOpen("");
      }, 2000);
    } else {
      setMessageStatus("error");
      form.resetFields();
      setMessageText(res.msg);
    }
  };

  const getList = async (params) => {
    setLoading(true);
    let res: any = await Https.post("/book/record/recordList", params, true);
    setLoading(false);
    let records = [];
    let total = 0;
    if (res.code == 200 && res.data) {
      records = res.data.records;
      total = res.data.total;
    } else {
      message.error(res.msg);
    }
    return { success: true, data: records, total };
  };
  const operate = {
    title: "操作",
    fixed: "right",
    dataIndex: "operator",
    hideInSearch: true,
    width: 150,
    align: "align",
    render: (_, record) => {
      return (
        <>
          {record.status == "2" && record.signinFlag == 0 && (
            <Button
              size="small"
              type="link"
              onClick={() => {
                setOpen("sign");
                setCourseId(record.id);
                form.resetFields();
                setMessageStatus("");
                setMessageText("");
                setTitle(
                  `签到(${record.wechatUserName}:${record.wechatUserPhone})`
                );
              }}
            >
              签到
            </Button>
          )}
          <Button
            size="small"
            type="link"
            onClick={() => {
              setOpen("details");
              setCourseId(record.id);
            }}
          >
            详情
          </Button>
          {record.status == "2" && (
            <Button
              size="small"
              type="link"
              onClick={() => cancelRecord(record)}
            >
              取消预约
            </Button>
          )}
        </>
      );
    },
  };
  return (
    <PageContainer title="私教课预约记录">
      <Fragment>
        <ProTable
          rowKey="id"
          actionRef={actionRef}
          //scroll={{ x: 1500 }}
          toolBarRender={() => [
            <Button
              key="add"
              type="primary"
              onClick={() => history.push(`/course/order/1`)}
            >
              代客预约
            </Button>,
          ]}
          request={async (reques) => {
            return await getList({ ...reques, courseType: 1 });
          }}
          pagination={{
            showSizeChanger: true,
          }}
          loading={loading}
          columns={calcColumns({ operate })}
        />
        {/* 预约记录详情 */}
        <Drawer
          title="预约记录详情(私教课)"
          onClose={() => {
            setOpen("");
          }}
          destroyOnClose={true}
          maskClosable={true}
          width="50%"
          open={open == "details"}
        >
          {open && <AppointmentDetails id={courseId} courseType={1} />}
        </Drawer>
        {/* 单个签到 */}
        <Modal
          title={title}
          open={open == "sign"}
          footer={null}
          onCancel={() => {
            setOpen("");
          }}
        >
          <Spin spinning={loading}>
            {messageStatus == "success" && (
              <Alert message="签到成功" type="success" showIcon />
            )}
            {messageStatus == "error" && (
              <Alert message={messageText} type="error" showIcon />
            )}
            <Form form={form} style={{ margin: "24px", height: "50px" }}>
              <Form.Item label="签到码" tooltip={"请输入6位数字"} name="code">
                <Input.OTP
                  formatter={(str) => str.replace(/\s/g, "").toUpperCase()}
                  onChange={onChangeText}
                  disabled={messageStatus == "success"}
                  ref={InputRef}
                />
              </Form.Item>
            </Form>
          </Spin>
        </Modal>
        {contextHolder}
      </Fragment>
    </PageContainer>
  );
};

export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(RecordList);
